package cn.java78.jdbc;

import cn.myschool.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author oldliu
 * @since 1.0
 */
public class TransactionDemo {
    public static void main(String[] args) {
        transfer("laowang","dingguo",200);
    }
    //转账
    public static void transfer(String from,String to,float m){
        Connection con=null;
        PreparedStatement ps=null;
        PreparedStatement ps2=null;
        String sql="update bank set money=money-? where acno=?";

        try {
            con= DBUtil.getConnection();
            con.setAutoCommit(false);//关闭自动提交
            ps=con.prepareStatement(sql);
            ps.setFloat(1,m);
            ps.setString(2,from);
            int r1=ps.executeUpdate();
            ps2=con.prepareStatement(sql);
            ps2.setFloat(1,-m);
            ps2.setString(2,to);
            int r2=ps2.executeUpdate();
            System.out.println("r1:"+r1+",r2:"+r2);
            if(r1>0&&r2>0)
                con.commit();//提交
            else
                con.rollback();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (Exception e1) {
                //e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            DBUtil.close(ps);
            DBUtil.close(ps2);
            DBUtil.close(con);
        }
    }
}
